package com.linking.config.manager;

import com.alibaba.nacos.api.exception.NacosException;
import com.linking.config.common.Constants;
import com.linking.config.pojo.BootstrapConfigBO;
import com.linking.config.util.FileUtils;
import java.io.File;
import java.io.IOException;
import lombok.extern.slf4j.Slf4j;

/**
 * @Author YaoWeiXin
 * @Date 2020/4/15 11:27
 * @Description 主配置管理器
 */
@Slf4j
public class MainConfigManager {

  private static BootstrapConfigBO bootstrapConfig;

  public static void load(String path) throws NacosException, IOException {
    loadBootstrapConfig(path);
    loadApplicationYaml();
  }

  private static void loadBootstrapConfig(String path) throws IOException {
    String filePath = FileUtils.getFilePath("bootstrap.yml", path);
    String bootstrap = FileUtils.readFileToString(new File(filePath));
    bootstrapConfig = BootstrapConfigBO.of(bootstrap);
  }

  public static BootstrapConfigBO getBootstrapConfig() {
    return bootstrapConfig;
  }

  /**
   * 初始应用配置
   */
  private static void loadApplicationYaml() throws NacosException {
    NacosConfigManager.loadConfig(bootstrapConfig.getAppDataId() + "-application.yml",
        MainConfigManager::writeApplicationYaml);
  }

  private static void writeApplicationYaml(String configContent) {
    try {
      String filePath = Constants.BOOTSTRAP_PATH.replaceAll("bootstrap.conf", "application.yml");
      FileUtils.write(new File(filePath), configContent, "UTF-8", false);
      log.info("application.yml is write:{}", configContent);
    } catch (IOException e) {
      log.error("启动报错:", e);
    }
  }
}
